package servlets.newUserServlets;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import managers.JsonManager;
import structures.User;

public class UserRegistrationServlet extends HttpServlet {

	private static final String URLBASE = "http://localhost:8080/ISellToYouRESTWebService/";
	private static final long serialVersionUID = 1465483806456919919L;
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response){
		String name, surname, email, password, cap, city, address, answer, inputLine, payPalEmail;
		BufferedReader reader;
		StringBuffer responseBuffer;
		User user = null;
		JsonManager jsonManager;
		jsonManager = new JsonManager();
		
		name = request.getParameter("name");
		surname = request.getParameter("surname");
		email = request.getParameter("email");
		password = request.getParameter("password");
		cap = request.getParameter("cap");
		city = request.getParameter("city");
		address = request.getParameter("address");
		payPalEmail = request.getParameter("payPalEmail");
		
		try {
			// Chiamo servlet del servizio globale per registrazione + mail di attivazione
			String url = URLBASE + "createUser?name="+ name + "&surname="+ surname + "&email="+ email + "&password="+ password + "&cap="+ cap + "&city="+ city + "&address="+ address + "&payPalEmail="+ payPalEmail;
			String cleanUrl = url.replace(" ", "%20");
			
			HttpURLConnection httpConnection = (HttpURLConnection) new URL(cleanUrl).openConnection();
			httpConnection.setRequestMethod("GET");
			httpConnection.setDoOutput(true); 
			httpConnection.setDoInput(true);
			httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			
			reader = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));

			responseBuffer = new StringBuffer();
			
			while ((inputLine = reader.readLine()) != null) {
				responseBuffer.append(inputLine);
			}
			reader.close();

			answer = responseBuffer.toString();
			

			if(answer.equals("null"))
				throw new Exception();
			
			user = jsonManager.toUser(answer);
			request.getSession().setAttribute("user", user);
			
			try {
				response.sendRedirect(request.getContextPath() + "/home.jsp");
			} catch (IOException e) {
				e.printStackTrace();
			}
		} catch (Exception e1) {
			request.getSession().setAttribute("error", "yes");
			try {
				response.sendRedirect(request.getContextPath() + "/registration.jsp");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}
